const express = require("express");
const router = express.Router();
const MySQL = require("../../mysql/mysql");
const Log = require("../../common/log");
const bodyParser = require("body-parser");
const Common = require("../../common/common");
const ResList = require("../../common/responseList");

// 配置body-parser
router.use(
  bodyParser.urlencoded({
    extended: true
  })
);
router.use(bodyParser.json());

/**
 * 笔记创建
 * 接收客户端传来的UserToken/NoteTitle/isSelf/NoteContent
 * 服务器端需要加入CreateTime
 * 服务器端需要对UserToken进行验证
 */

router.post("/createnote.node", (req, res) => {
  let date = new Date();
  // 接收客户端传入的参数
  let reqData = {
    UserToken: req.body.UserToken,
    NoteTitle: req.body.NoteTitle,
    NoteContent: req.body.NoteContent,
    isSelf: req.body.isSelf,
    CreateTime:Common.dateFormat(date),
  };
  //验证客户端传过来的数据
  if(reqData.UserToken && reqData.NoteTitle && reqData.isSelf){
    MySQL.Mysql('INSERT INTO s_note SET ?',reqData,(err,results,fields)=>{
      if(err){
        throw err;
        // 响应客户端
        ResList.ResList(req, res, '1', '笔记保存失败', {});
        Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '1', '笔记保存失败',reqData.UserToken);
      }else{
        // 响应客户端
        ResList.ResList(req, res, '0', '保存成功', {});
        Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '1', '保存成功',reqData.UserToken);
      }
    })  
  }else{
    // 响应客户端
    ResList.ResList(req, res, '-2', '空指针异常', {});
    if(reqData.UserToken){
      // 记录日志
		Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '-2', '空指针异常',reqData.UserToken);
    }else{
      // 记录日志
		Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '-2', '空指针异常','');
    }
  }
});

module.exports = router;
